package io.jee.medusa.transfer;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class EmptyTransfer {

	public static <T> T transfer(Map<String, Object> map, Class<T> clz) {
		T t = null;
		try {
			if (map == null) {
				return null;
			}
			t = clz.newInstance();
			Method[] methods = clz.getMethods();
			Method method = null;
			Object value = null; 
			for (String key : map.keySet()) {
				method = getSetter(methods, key);
				if (method != null) {
					value = map.get(key);
					method.invoke(t, value);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return t;
	}
	
	
	
	public static <T> List<T> transfer(List<Map<String, Object>> datas, Class<T> clz) {
		List<T> result = null;
		try {
			if (datas == null || datas.size() == 0) {
				return null;
			}
			result = new ArrayList<T>();
			for (Map<String, Object> map : datas) {
				result.add(transfer(map, clz));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	
	private static Method getSetter(Method[] methods, String key) {
		Method method = null;
		String first = key.substring(0, 1).toUpperCase();
		String setter = "set" + first + key.substring(1);
		for (Method m : methods) {
			if (m.getName().equals(setter)) {
				method = m;
				break;
			}
		}
		return method;
	}
}
